<script setup>
import {computed, ref, watch} from 'vue'

defineProps({
  msg: String,
})
const savedTodos = localStorage.getItem('todos');
const todos = ref(savedTodos ? JSON.parse(savedTodos) : [])
const newTodo = ref('')
const filter = ref('all')

// 添加Todo
const addTodo = () => {
  if (newTodo.value.trim()) {
    todos.value.push({
      id: Date.now(),
      text: newTodo.value.trim(),
      completed: false
    });
    newTodo.value = '';
  }
}
// 删除todo
const removeTodo = (todoId) => {
  todos.value = todos.value.filter(todo => todo.id !== todoId)
}

// 计算属性，根据过滤条件返回过滤后的待办事项列表
const filteredTodos = computed(()=> {
  switch (filter.value) {
    case 'active':
      return todos.value.filter(todo=> todo.completed === false);
    case 'completed':
      return todos.value.filter(todo=>todo.completed === true);
    default:
      return todos.value
  }
});

// 监听todos的变化并保存到本地存储
watch(todos, (newTodos) => {
  localStorage.setItem('todos', JSON.stringify(newTodos));
}, {deep: true});
</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <el-input v-model="newTodo" placeholder="添加待办事项" />
    <el-button @click="addTodo">添加</el-button>
    <ul>
      <li v-for="todo in filteredTodos" :key="todo.id">
        <el-checkbox v-model="todo.completed" />
        <span :class="{'completed': todo.completed }">{{ todo.text }}</span>
        <el-button @click="removeTodo(todo.id)" type="danger">删除</el-button>
      </li>
    </ul>
    <button @click="filter = 'all'">全部</button>
    <button @click="filter = 'active'">活动中</button>
    <button @click="filter = 'completed'">已完成</button>
  </div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
